import redis
import sys
import os
import urllib3
import queue
import random
import string
import urllib.parse
# 最大线程数
MAX_WORKERS = 16

DEBUG = False 
DEBUG = True #本地调试


sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', buffering=1)  # 行缓冲
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

#redis 服务器
if DEBUG:
    MAX_WORKERS = 1
    Q = queue.Queue()
    R = redis.Redis(host='127.0.0.1', port=6379, db=3)
else:
    Q = queue.Queue()
    R = redis.Redis(host='localhost', port=6379, db=3)
# 测试redis是否连接成功
try:
    R.ping()
    print(f"Redis 连接成功!")
except redis.ConnectionError:
    print(f"Redis 连接失败，请检查服务器是否启动")
# 远程数据库推送地址
REMOTE_DB_PUSH_URL_LAST = "http://xdrj.lottefuture.com/zxy/V1/Gen2/ed1XF/lineReportController/receive/method"
REMOTE_DB_PUSH_URL_NEXT = "https://xf-162.lottefuture.com/api/weiboPush"
REMOTE_DB_PUSH_URL_NEXT_BEN = "http://127.0.0.1:88/xingfan/public/index.php/api/weiboPush"

if DEBUG:
    URLS=[
       REMOTE_DB_PUSH_URL_NEXT,
       # REMOTE_DB_PUSH_URL_NEXT_BEN
    ]
else:
    URLS=[
        REMOTE_DB_PUSH_URL_LAST,
        REMOTE_DB_PUSH_URL_NEXT

    ]

#解析接口
PARSE_PRODUCT="http://cgi-bin.lottefuture.com/python/link-parse.php"
#没有解析出来的产品url
NO_PARSE_DEFAULT_URL="https://uland.taobao.com/coupon/edetail?itemId=prbDpZjUxt6z52MseAOIptm-9za58Xoh72J0DyWWHrR"

if  DEBUG:
    COOKIE_PATH = r"./weibo_cookies.json"
    COOKIE_PATH2 = r"./cookies.json"
else:
    COOKIE_PATH = r"./weibo_cookies.json"
    COOKIE_PATH2 = r"./cookies.json"

def get_random_user_agent():
    """获取随机用户代理"""
    user_agents = [
        'Windows',
        'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1',
        'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        'Mozilla/5.0 (iPad; CPU OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        'Mozilla/5.0 (Linux; Android 10; SM-G981B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Mobile Safari/537.36',
        'Mozilla/5.0 (Linux; Android 10; SM-G980F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Mobile Safari/537.36',
    ]
    return random.choice(user_agents)
def getCookie():
    with open(COOKIE_PATH, mode="r",encoding="utf-8") as f:
        cookies = f.read()
    return cookies 
HEADERS = {
    'sec-ch-ua-platform': '"Windows"',
    "sec-ch-ua-mobile":"?0",
    "upgrade-insecure-requests:":'1',
    #'Referer': 'https://m.weibo.cn',
    'sec-ch-ua': '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
    "Connection": "close",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
}

# 获取随机cookie
def generate_weibo_cookie(user_id=None):
    """
    生成类似微博的Cookie字符串
    
    Args:
        user_id: 目标用户ID，如果不提供则随机生成
    
    Returns:
        str: 生成的Cookie字符串
    """
    # 固定部分
    fixed_parts = {
        '_T_WM': '43533594811',
        'WEIBOCN_FROM': '1110006030',
        'MLOGIN': '0'
    }
    
    # 变化部分 - 随机生成
    xsrf_token = ''.join(random.choices('0123456789abcdef', k=6))
    short_token = ''.join(random.choices('0123456789abcdef', k=10))
    
    # 如果未提供用户ID，则随机生成一个
    if user_id is None:
        user_id = ''.join(random.choices('0123456789', k=10))
    
    # 构建URL编码的参数
    params = {
        'luicode': '10000011',
        'lfid': f'107603{user_id}',
        'fid': f'100505{user_id}',
        'uicode': '10000011'
    }
    encoded_params = urllib.parse.urlencode(params)
    
    # 构建完整Cookie
    cookie_parts = [
        f"{k}={v}" for k, v in fixed_parts.items()
    ]
    cookie_parts.extend([
        f"XSRF-TOKEN={xsrf_token}",
        f"mweibo_short_token={short_token}",
        f"M_WEIBOCN_PARAMS={encoded_params}"
    ])
    
    return "; ".join(cookie_parts)
random_cookie = generate_weibo_cookie()
# 设置完整的请求头，模拟真实浏览器访问
HEADERS = {
    'User-Agent': get_random_user_agent(),
    'Accept': 'application/json, text/plain, */*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': f'https://m.weibo.cn/api/container/getIndex?type=uid&value=5069029750&containerid=1076035069029750&since_id=5203128241884766',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',
    'X-Requested-With': 'XMLHttpRequest',
    'Connection': 'keep-alive',
    'Sec-Fetch-Dest': 'cross-site',
    'Sec-Fetch-Mode': 'no-cors',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-User':'?1',
    'Pragma': 'no-cache',
    'Cache-Control': 'no-cache',
    'sec-ch-ua': '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'upgrade-insecure-requests': '1',
    #'Host'  :  'm.weibo.cn',
    'Cookie': random_cookie
}

# 隧道域名:端口号
tunnel = "tun-festhu.qg.net:17690"

# 用户名密码方式
username = "E5F6D6EE"
password = "9B219197EE72"


PROXY = {
    "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel},
    "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel}
    }

#PROXY =None




if DEBUG:
    URLS_PATH = './urls.txt'
    BLOCK_KEYWORD_PATH = './block_keyword.txt'
    JS_PATH='./pass_by_selenium/drag_captcha'
    DRIVER_PATH = "./chromedriver-ben/chromedriver.exe"
else:    

    DRIVER_PATH = "./chromedriver-xian/chromedriver.exe"
    URLS_PATH = './urls.txt'
    BLOCK_KEYWORD_PATH = './block_keyword.txt'
    JS_PATH='./pass_by_selenium/drag_captcha'




